import datetime
import json
import asyncio
import time
import logging

logger = logging.getLogger("main")
file = "data.json"
lock = asyncio.Lock()


def is_today(timestamp):
    try:
        date_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
        current_date = datetime.datetime.now()
        return date_from_timestamp.date() == current_date.date()
    except Exception as e:
        logger.error(f"An error occurred: {e}")
        return False


async def read_data():
    global lock
    default = {
        "today": 0,
        "total": 0,
        "time": 0,
        "need_gen": 0,
        "need_gen_refresh_time": 0,
    }
    try:
        async with lock:
            with open(file, "r") as f:
                ret = json.loads(f.read())
    except:
        ret = default
    for k in default:
        if not k in ret:
            ret[k] = default[k]
    return ret


async def save_data(data):
    global lock
    async with lock:
        with open(file, "w") as f:
            f.write(json.dumps(data))


async def add_gen(gen):
    data = await read_data()
    if not is_today(data["time"]):
        data["today"] = 0
        data["time"] = time.time()
    data["today"] += gen
    data["total"] += gen
    await save_data(data)
    return data


async def read_need():
    data = await read_data()
    t = time.time()
    if t - data["need_gen_refresh_time"] > 60 * 60:
        from libs.request import get_list, deal_genshin_character_list_data

        listGenshinCharacter = await get_list()
        cost, total, magic = deal_genshin_character_list_data(listGenshinCharacter)
        await save_need(total - cost, data)
    return data["need_gen"]


async def save_need(gen, data=None):
    if not data:
        data = await read_data()
    data["need_gen"] = gen
    data["need_gen_refresh_time"] = time.time()
    await save_data(data)
